<template>
  <div class="article-edit-container">
    <a-card :title="isEdit ? '编辑文章' : '新增文章'" :bordered="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
        @finish="handleSubmit"
      >
        <a-row :gutter="16">
          <a-col :span="16">
            <!-- 文章标题 -->
            <a-form-item label="文章标题" name="title">
              <a-input v-model:value="formState.title" placeholder="请输入文章标题" />
            </a-form-item>

            <!-- 文章摘要 -->
            <a-form-item label="文章摘要" name="summary">
              <a-textarea
                v-model:value="formState.summary"
                placeholder="请输入文章摘要"
                :auto-size="{ minRows: 3, maxRows: 5 }"
              />
            </a-form-item>

            <!-- 文章内容 -->
            <a-form-item label="文章内容" name="content">
              <div class="editor-container">
                <a-textarea
                  v-model:value="formState.content"
                  placeholder="请输入文章内容，支持HTML格式"
                  :auto-size="{ minRows: 15, maxRows: 30 }"
                />
              </div>
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <!-- 文章封面 -->
            <a-form-item label="文章封面" name="coverImage">
              <div class="cover-uploader">
                <div v-if="formState.coverImage" class="cover-preview">
                  <img :src="formState.coverImage" alt="封面预览" />
                  <div class="cover-actions">
                    <a-button type="primary" size="small" @click="handleChangeCover">更换</a-button>
                    <a-button danger size="small" @click="handleRemoveCover">移除</a-button>
                  </div>
                </div>
                <a-upload
                  v-else
                  name="file"
                  list-type="picture-card"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  @change="handleCoverChange"
                  :customRequest="handleCustomUpload"
                  :action="null"
                >
                  <div v-if="uploadLoading">
                    <loading-outlined />
                    <div style="margin-top: 8px">上传中...</div>
                  </div>
                  <div v-else>
                    <plus-outlined />
                    <div style="margin-top: 8px">上传封面</div>
                  </div>
                </a-upload>
              </div>
            </a-form-item>

            <!-- 作者信息 -->
            <a-form-item label="作者" name="author">
              <a-input v-model:value="formState.author" placeholder="请输入作者姓名" />
            </a-form-item>

            <a-form-item label="作者职称" name="authorTitle">
              <a-input v-model:value="formState.authorTitle" placeholder="请输入作者职称" />
            </a-form-item>

            <a-form-item label="所属医院" name="hospital">
              <a-input v-model:value="formState.hospital" placeholder="请输入所属医院" />
            </a-form-item>

            <a-form-item label="所属科室" name="department">
              <a-input v-model:value="formState.department" placeholder="请输入所属科室" />
            </a-form-item>

            <!-- 文章分类 -->
            <a-form-item label="文章分类" name="category">
              <a-select v-model:value="formState.category" placeholder="请选择文章分类">
                <a-select-option v-for="category in categories" :key="category.code" :value="category.code">
                  {{ category.name }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 文章标签 -->
            <a-form-item label="文章标签">
              <a-select
                v-model:value="formState.tags"
                mode="tags"
                style="width: 100%"
                placeholder="请输入标签，回车确认"
              ></a-select>
            </a-form-item>

            <!-- 文章状态 -->
            <a-form-item name="isPublished" label="发布状态">
              <a-switch
                v-model:checked="formState.isPublished"
                checked-children="已发布"
                un-checked-children="草稿"
              />
            </a-form-item>

            <!-- 是否推荐 -->
            <a-form-item name="isRecommended" label="是否推荐">
              <a-switch
                v-model:checked="formState.isRecommended"
                checked-children="推荐"
                un-checked-children="普通"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 表单按钮 -->
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="submitting">保存</a-button>
            <a-button @click="goBack">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import {
  getArticleDetail,
  createArticle,
  updateArticle,
  getArticleCategories,
  uploadArticleImage
} from '@/api/article';

export default defineComponent({
  components: {
    PlusOutlined,
    LoadingOutlined
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const formRef = ref();
    const articleId = computed(() => route.params.id);
    const isEdit = computed(() => !!articleId.value && articleId.value !== 'new');
    const categories = ref([]);
    const submitting = ref(false);
    const uploadLoading = ref(false);

    // 表单数据
    const formState = reactive({
      title: '',
      summary: '',
      content: '',
      coverImage: '',
      author: '',
      authorTitle: '',
      hospital: '',
      department: '',
      category: '',
      tags: [],
      isPublished: true,
      isRecommended: false
    });

    // 表单验证规则
    const rules = {
      title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
      summary: [{ required: true, message: '请输入文章摘要', trigger: 'blur' }],
      content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
      author: [{ required: true, message: '请输入作者姓名', trigger: 'blur' }],
      category: [{ required: true, message: '请选择文章分类', trigger: 'change' }]
    };

    // 获取文章详情
    const fetchArticleDetail = async () => {
      if (!isEdit.value) return;

      try {
        const res = await getArticleDetail(articleId.value);
        if (res.code === 0 && res.data) {
          const article = res.data;
          Object.keys(formState).forEach(key => {
            if (key in article) {
              formState[key] = article[key];
            }
          });
        } else {
          message.error(res.message || '获取文章详情失败');
        }
      } catch (error) {
        console.error('获取文章详情失败:', error);
        message.error('获取文章详情失败');
      }
    };

    // 获取文章分类
    const fetchCategories = async () => {
      try {
        const res = await getArticleCategories();
        if (res.code === 0) {
          categories.value = res.data;
        } else {
          message.error(res.message || '获取文章分类失败');
        }
      } catch (error) {
        console.error('获取文章分类失败:', error);
        message.error('获取文章分类失败');
      }
    };

    // 提交表单
    const handleSubmit = async () => {
      submitting.value = true;
      try {
        const values = { ...formState };

        if (isEdit.value) {
          // 更新文章
          const res = await updateArticle(articleId.value, values);
          if (res.code === 0) {
            message.success('更新成功');
            goBack();
          } else {
            message.error(res.message || '更新失败');
          }
        } else {
          // 创建文章
          const res = await createArticle(values);
          if (res.code === 0) {
            message.success('创建成功');
            goBack();
          } else {
            message.error(res.message || '创建失败');
          }
        }
      } catch (error) {
        console.error('保存文章失败:', error);
        message.error('保存失败');
      } finally {
        submitting.value = false;
      }
    };

    // 上传前检查
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
      }
      return isImage && isLt2M;
    };

    // 自定义上传处理函数
    const handleCustomUpload = async ({ file, onProgress, onSuccess, onError }) => {
      uploadLoading.value = true;
      try {
        const formData = new FormData();
        formData.append('file', file);
        
        // 调用API上传图片
        const res = await uploadArticleImage(formData);
        if (res.code === 0) {
          formState.coverImage = res.data.url;
          onSuccess(res, file);
        } else {
          onError(new Error(res.message || '上传失败'));
        }
      } catch (error) {
        console.error('上传封面失败:', error);
        onError(error);
        message.error('上传封面失败: ' + (error.message || '未知错误'));
      } finally {
        uploadLoading.value = false;
      }
    };

    // 处理封面上传
    const handleCoverChange = (info) => {
      if (info.file.status === 'uploading') {
        uploadLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        uploadLoading.value = false;
        // 如果使用自定义上传，则已在handleCustomUpload中设置封面URL
        if (!formState.coverImage && info.file.response && info.file.response.data) {
          formState.coverImage = info.file.response.data.url;
        }
      } else if (info.file.status === 'error') {
        uploadLoading.value = false;
        message.error('上传失败');
      }
    };

    // 更换封面
    const handleChangeCover = () => {
      formState.coverImage = '';
    };

    // 移除封面
    const handleRemoveCover = () => {
      formState.coverImage = '';
    };

    // 返回上一页
    const goBack = () => {
      router.push('/articles');
    };

    onMounted(() => {
      fetchCategories();
      fetchArticleDetail();
    });

    return {
      formRef,
      formState,
      rules,
      categories,
      isEdit,
      submitting,
      uploadLoading,
      handleSubmit,
      beforeUpload,
      handleCoverChange,
      handleChangeCover,
      handleRemoveCover,
      handleCustomUpload,
      goBack
    };
  }
});
</script>

<style scoped>
.article-edit-container {
  padding: 24px;
}

.cover-uploader {
  width: 100%;
}

.cover-preview {
  position: relative;
  width: 100%;
  margin-bottom: 16px;
}

.cover-preview img {
  width: 100%;
  max-height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.cover-actions {
  position: absolute;
  bottom: 8px;
  right: 8px;
  display: flex;
  gap: 8px;
}

.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  min-height: 400px;
}
</style> 